package com.study.ktandroid.coroutines_apply.apply.vm

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.study.ktandroid.coroutines_apply.apply.bean.LoadState
import com.study.ktandroid.coroutines_apply.apply.launch
import com.study.ktandroid.coroutines_apply.apply.network.NetworkService
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

// 一个页面一个ViewModel这种方法可行
// 如果ViewModel多了，getData方法就成了模板方法（   viewModelScope.launch(CoroutineExceptionHandler { _, e ->）很冗余
// 一种做法是可以创建BaseViewModel将模板代码放到父类中，但是这种做法缺点是想法开发到一定阶段需求父类的做法不好
// 可以为ViewModel添加扩展方法
class MainViewModel : ViewModel() {
    // 图片集合
    val imageList = MutableLiveData<List<String>>()

    // 加载状态
    val loadState = MutableLiveData<LoadState>()

    // 使用扩展函数
    fun getData() {
        launch({
            loadState.value = LoadState.Loading()
            // 并发请求三次加载图片
            val data1 = async { NetworkService.apiService.getImage() }
            val data2 = async { NetworkService.apiService.getImage() }
            val data3 = async { NetworkService.apiService.getImage() }
            // 更新UI
            imageList.value = listOf(data1.await(), data2.await(), data3.await()).map {
                it.imgurl
            }
        }, {
            loadState.value = LoadState.Fail(it.message ?: "加载失败")
        }, { loadState.value = LoadState.Success() })
    }

    fun getData1() {
        viewModelScope.launch(CoroutineExceptionHandler { _, e ->
            loadState.value = LoadState.Fail(e.message ?: "加载失败")
        }) {
            loadState.value = LoadState.Loading()
            // 并发请求三次加载图片
            val data1 = async { NetworkService.apiService.getImage() }
            val data2 = async { NetworkService.apiService.getImage() }
            val data3 = async { NetworkService.apiService.getImage() }
            // 更新UI
            imageList.value = listOf(data1.await(), data2.await(), data3.await()).map {
                it.imgurl
            }

            // 更新状态
            loadState.value = LoadState.Success()
        }
    }
}